package com.zy.rushjdcloud.task;

import com.zy.rushjdcloud.RushRequestParams;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author zy
 * @date 2019-10-4 11:48
 */
@Data
@AllArgsConstructor
@Slf4j
public class RushTask {
    /**
     * 线程池
     */
    private ThreadPoolExecutor pool;

    /**
     * 请求参数相关封装
     */
    private RushRequestParams rushRequestParams;


    public void doRush(Map<String, List<String>> msg) {
        try {
            LocalDateTime now = LocalDateTime.now();
            String nowStr = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            List<String> msgList = new LinkedList<>();
            msg.put(nowStr, msgList);
            for (int i = 0; i < 20; i++) {
                Thread.sleep(50L);
                pool.execute(() -> {
                    try {
                        DefaultHttpClient client = new DefaultHttpClient();
                        HttpPost post = new HttpPost(rushRequestParams.getTargetUrl());
                        StringEntity entity = new StringEntity(rushRequestParams.getParam(), "utf-8");
                        post.setEntity(entity);
                        post.setHeader("Cookie", rushRequestParams.getCookie());
                        post.setHeader("Referer", rushRequestParams.getReferer());
                        post.setHeader("Content-Type", "application/json;charset=UTF-8");
                        log.info("任务执行时刻 {}", LocalDateTime.now());
                        HttpResponse response = client.execute(post);
                        log.info("任务执行完成时刻 {}", LocalDateTime.now());
                        String result = EntityUtils.toString(response.getEntity(), "utf-8");
                        log.info(result);
                        msgList.add(result);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
